/**
*    Copyright (C) 2008  Chase Kernan 
*    chase.kernan@gmail.com
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
* 
*/

package com.chasekernan.hxnova.core.dataholders;

import com.chasekernan.hxnova.core.players.Player;

/**
    Contains all of the players in the game.
    Note: the [nullPlayer] is used for stars and fleets that don't have an 
    owner.
**/
class Players {
    
    public var players : Array<Player>;
    
    public var nullPlayer : Player;
    
    public function new() {
        players = new Array();
        nullPlayer = new Player();
        nullPlayer.id = -1;
    }
    
    /**
        Adds a player to the end of the list and adjusts the id accordingly.
    **/
    public function addPlayer(p : Player) {
        p.id = players.length;
        players.push(p);
    }
    
    /**
        Returns the player with the given id.
        Will throw an error if the id is out of range.
        Note: the [nullPlayer] has an id of 0.
    **/
    public function getPlayerById(id : Int) : Player {
        if (id < -1 || id >= players.length) throw "Player id is out of range.";
        if (id == -1) return nullPlayer;
        return players[id];
    }
    
    public function iterator() {
        return players.iterator();
    }
    
    public static var XML_TITLE = "players";
    
    public static function writeToXml(players : Players) : Xml {
        var xml = Xml.createElement(XML_TITLE);
        for (p in players.players) {
            xml.addChild(Player.writeToXml(p));
            xml.addChild(Xml.createElement("spacer"));
        }
        
        return xml;
    }
        
    public static function readFromXml(xml : Xml) : Players {
        try {
            var players = new Players();
            
            for (e in xml.elementsNamed(Player.XML_TITLE)) {
                var p = Player.readFromXml(e);
                players.players[p.id] = p;
            }
            
            return players;
        } catch (e : Dynamic) {
            throw "Error while reading players file from xml: " + e;
        }
    }
    
}